package br.ufpi.hu.prescricao.facade.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.naming.NamingException;

import br.ufpi.hu.prescricao.dao.LaudoDAO;
import br.ufpi.hu.prescricao.facade.LaudoFacade;
import br.ufpi.hu.prescricao.facade.UserFacade;
import br.ufpi.hu.prescricao.model.Laudo;
import br.ufpi.hu.prescricao.model.Usuario;


@Stateless
public class LaudoFacadeImpl implements LaudoFacade {

	@EJB
	private LaudoDAO laudoDAO;

	@EJB
	private UserFacade userFacade;

	@Override
	public void save(Laudo prescricao) {
		
		//salva usuario da sessao
		prescricao.setUsuarioDaSessao(userFacade.getUsuarioAtual());
		
		laudoDAO.save(prescricao);
		
	}

	@Override
	public Laudo find(int entityID) {
		Laudo relatorio = laudoDAO.find(entityID);
		return relatorio;
	}

	@Override
	public List<Laudo> findAll() throws NamingException {
		
		Map<String,String> ordenacao = new HashMap<String, String>();

		ordenacao.put("dataDeCriacao","desc");

		Usuario usuarioAtual = userFacade.getUsuarioAtual();

		if (userFacade.isUsuarioAtualAdmin()) {
			return laudoDAO.findAll(ordenacao,null);
		}
		else {
			return laudoDAO.findAllByUser(usuarioAtual, ordenacao);
		}
	}

	@Override
	public List<Laudo> findAllFiltroDataPaciente(Date dataInicial, Date dataFinal, Integer pacienteId) {
		
		Map<String,String> ordenacao = new HashMap<String, String>();

		ordenacao.put("dataDeCriacao","desc");

		Usuario usuarioAtual = userFacade.getUsuarioAtual();
		
		return laudoDAO.findAllFiltroDataPaciente( 
				userFacade.isUsuarioAtualAdmin() ? null : usuarioAtual,
				ordenacao,
				dataInicial,
				dataFinal,
				pacienteId,
				0,
				0
				);
	}

	@Override
	public LaudoDAO getLaudoDAO() {
		return laudoDAO;
	}
	
	@Override
	public void delete(Laudo laudo) {
		laudoDAO.delete(laudo);
	}
	
	@Override
	public void update(Laudo laudo) {
		laudoDAO.update(laudo);
	}
	
	
}